package com.wanxi.controller.other;

import com.wanxi.dto.ResultDTO;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;
/**
 * @author Chengbo Zhang
 */
@RestController
@CrossOrigin(origins = "http://localhost:8081")
public class FileUploadController {
    /**
     * 上传文件存储目录
     */
    private static final String UPLOAD_DIRECTORY = "img";

    @Value("${file.webDirectory}")
    private String webDirectory;

    @Value("${file.uploadDirectory}")
    private String uploadDirectory;
    @PostMapping("/upload")
    public ResultDTO upload(HttpServletRequest req) throws IOException {
        // 检测是否为多媒体上传
        if (!ServletFileUpload.isMultipartContent(req)) {
            // 如果不是则停止
            return ResultDTO.builder().msg("Error: 表单必须包含 enctype=multipart/form-data").code(1).data(null).count(0).build();
        }

        // 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中

        // 设置临时存储目录

        //解析文件
        ServletFileUpload upload = new ServletFileUpload(factory);

        // 中文处理
        upload.setHeaderEncoding("UTF-8");

        // 构造临时路径来存储上传的文件
        // 这个路径相对当前应用的目录
        String uploadPath = uploadDirectory+ UPLOAD_DIRECTORY;

        createDirectory(uploadPath);

        try {
            //解析请求的内容提取文件数据
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(req);

            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
//                        文件名称
                        String fileName = new File(item.getName()).getName();
//                        文件名不能一样，所以在文件名前面加了一个时间戳
                        fileName = System.currentTimeMillis() + fileName;
//                        文件保存的绝对路径
                        String filePath = uploadPath +"/" + fileName;
                        File tempFile = new File(filePath);
                        // 保存文件到硬盘
                        item.write(tempFile);
//                        拷贝一份文件到web目录下
                        String webPath = webDirectory + UPLOAD_DIRECTORY + "/";
                        createDirectory(webPath);
                        copyFile(tempFile, fileName ,webPath);
                        return ResultDTO.getDTO(0, "/" + UPLOAD_DIRECTORY + "/" + fileName);
                    }
                }
            }
        } catch (Exception ex) {
            req.setAttribute("message",
                    "错误信息: " + ex.getMessage());
        }

        return null;
    }

    private void createDirectory(String path) {
        // 如果目录不存在则创建
        File uploadDir = new File(path);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
    }

    private void copyFile(File tempFile, String fileName,String webPath) {
        File webFile = new File(webPath, fileName);
        try {
            InputStream inputStream = new FileInputStream(tempFile);
            OutputStream outputStream = new FileOutputStream(webFile);

            int read = 0;
            while ((read = inputStream.read()) != -1) {
                outputStream.write(read);
            }

            inputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
